<?php

namespace app\school\controller;

use app\common\controller\BasicAdmin;
use app\common\model\CourseAttendanceModel;
use app\common\model\CourseModel;
use app\common\model\UserModel;
use app\common\model\UserTimesModel;
use app\common\traits\SelectPage;

class Student extends BasicAdmin
{
    use SelectPage;
    public $model = 'UserModel';

    /**
     * 学生列表
     */
    public function index()
    {
        $school_id = session('school_user.school_id');
        return  $this->_query($this->model)
            ->where('school_id',$school_id)
            ->like('nickname,phone')
            ->with(['school','schoolgrade','schoolclass'])
            ->where('role', 1)
            ->page();
    }

    /**
     * 详情
     */
    public function detail()
    {
        $user_id = $this->request->get('id');
        $user =  UserModel::where('id',$user_id)->with(['school','schoolgrade','schoolclass'])->find();
        //常规
        $user['normal'] = CourseModel::where('status',1)
            ->where('type',1)
            ->where('school_id',$user['school_id'])
            ->where('grade_id='.$user['grade_id'].' or grade_id is null')
            ->where('class_id='.$user['class_id'].' or class_id is null')
            ->select();
        //兴趣
        $course_ids = UserTimesModel::where('user_id',$user['id'])
            ->field('group_concat(course_id) as course_ids')->find()['course_ids'];
        $user['interest'] = CourseModel::where('status',1)
            ->where('type',2)
            ->where('id','in',$course_ids)
            ->select();
        //考勤
        $attendance = CourseAttendanceModel::where('find_in_set(in_userids,'.$user_id.')')->select();
        foreach ($attendance as $key=>$value){
            $value['course_name'] = CourseModel::where('id',$value['course_id'])->value('name');
        }
        $user['attendance'] = $attendance;
        //获取学生的学习时长与次数
        $user['count'] = CourseAttendanceModel::where('find_in_set('.$user['id'].',in_userids)')->count();
        $user['time'] =  ceil(45*$user['count']/60);
        $this->assign('user',$user);
        $this->fetch();
    }

    /**
     * 编辑
     */
    public function edit()
    {
        $this->title = '编辑';
        return $this->_form($this->model, 'form');
    }

    /**
     * 设置真实姓名
     */
    public function set_realname()
    {
        $this->title = '编辑';
        return $this->_form($this->model, 'realname');
    }
}